import { Module } from "vuex"
import router from "@/router"

import { ILoginState } from "./types"
import { IRootState } from "../types"
import { accountLoginRequest, requestUserInfo, requestMenu } from "@/service/login/login"
import { IAccount } from "@/service/login/types"
import cache from "@/utils/cache"

import { mapMenusToRoutes, mapMenusToPermissions } from "@/utils/map-menus"

// module 1 导入第一个参数传入当前 state 定义类型 2 第二个参数传入 跟state 定义类型
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, info: any) {
      state.userInfo = info
    },
    chengeuserMenus(state, menu: any) {
      state.userMenus = menu
      // 处理动态路由
      const path = mapMenusToRoutes(menu)
      path.forEach((item) => {
        router.addRoute("index", item)
      })

      // 获取用户按钮权限
      const permissions = mapMenusToPermissions(menu)
      state.permissions = permissions
    }
  },
  getters: {},
  // 发送网络请求
  actions: {
    async accoutLoginAction({ commit }, payload: IAccount) {
      // 1 实现登录逻辑
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit("changeToken", token)
      cache.setLocation("token", token)
      // 2 请求用户信息
      const userInfoResult = await requestUserInfo(id)
      const userinfo = userInfoResult.data
      commit("changeUserInfo", userinfo)
      cache.setLocation("userinfo", userinfo)

      // 3 查询菜单
      const menusResult = await requestMenu(userinfo.role.id)
      const menu = menusResult.data
      commit("chengeuserMenus", menu)
      cache.setLocation("menu", menu)

      // 4 跳转首页
      router.push("/index")
    },
    loadLocalLogin({ commit }) {
      const token = cache.getLocation("token")
      if (token) {
        commit("changeToken", token)
      }
      const userInfo = cache.getLocation("userinfo")
      if (userInfo) {
        commit("changeUserInfo", userInfo)
      }
      const menu = cache.getLocation("menu")
      if (menu) {
        commit("chengeuserMenus", menu)
      }
    }
  }
}

export default loginModule
